﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Linq.Expressions;

namespace SmartLib.Reflection.Dynamic
{
    /// <summary>
    /// 动态构造函数
    /// </summary>
    public static class DynamicConstructor
    {
        public delegate object InvokeConstructor();

        /// <summary>
        /// 编译动态构造函数（无参构造函数）
        /// </summary>
        /// <param name="type">类型</param>
        /// <returns></returns>
        public static InvokeConstructor CompileConstructor(Type type)
        {
            ConstructorInfo constructorInfo = type.GetConstructor(new Type[0] { });

            NewExpression newExpression = Expression.New(constructorInfo);

            UnaryExpression castMethodCall = Expression.Convert(newExpression, typeof(object));

            return Expression.Lambda<InvokeConstructor>(castMethodCall).Compile();
        }
    }
}
